#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <regex.h>

// 解析x.txt文件中的DW_OP_addr信息
void parse_dwarf_addr_from_file(const char* filename) {
    FILE* file = fopen(filename, "r");
    if (!file) {
        printf("无法打开文件: %s\n", filename);
        return;
    }
    
    printf("=== DW_OP_addr地址信息解析 ===\n");
    printf("文件: %s\n\n", filename);
    
    char line[1024];
    int line_num = 0;
    char current_var_name[100] = "未知变量";
    
    while (fgets(line, sizeof(line), file)) {
        line_num++;
        
        // 查找变量名行
        if (strstr(line, "DW_AT_name")) {
            // 查找变量名（在DW_AT_name后面的空格之后）
            char* name_start = strstr(line, "DW_AT_name");
            if (name_start) {
                name_start += strlen("DW_AT_name");
                // 跳过空格
                while (*name_start == ' ' || *name_start == '\t') name_start++;
                
                // 复制变量名直到行尾或空格
                int i = 0;
                while (name_start[i] != '\0' && name_start[i] != '\n' && name_start[i] != ' ' && name_start[i] != '\t') {
                    if (i < sizeof(current_var_name) - 1) {
                        current_var_name[i] = name_start[i];
                        i++;
                    } else {
                        break;
                    }
                }
                current_var_name[i] = '\0';
            }
        }
        
        // 查找DW_OP_addr地址行
        if (strstr(line, "DW_OP_addr")) {
            // 提取地址
            char* addr_start = strstr(line, "0x");
            if (addr_start) {
                char addr_str[32];
                int i = 0;
                while (i < 31 && (addr_start[i] >= '0' && addr_start[i] <= '9') || 
                       (addr_start[i] >= 'a' && addr_start[i] <= 'f') || 
                       (addr_start[i] >= 'A' && addr_start[i] <= 'F') || 
                       addr_start[i] == 'x') {
                    addr_str[i] = addr_start[i];
                    i++;
                }
                addr_str[i] = '\0';
                
                printf("第 %d 行:\n", line_num);
                printf("  变量: %s\n", current_var_name);
                printf("  DW_OP_addr地址: %s\n", addr_str);
                printf("  完整行内容: %s", line);
                printf("\n");
            }
        }
    }
    
    fclose(file);
}

int main(int argc, char* argv[]) {
    if (argc != 2) {
        printf("用法: %s <DWARF信息文件>\n", argv[0]);
        printf("示例: %s x.txt\n", argv[0]);
        return 1;
    }
    
    parse_dwarf_addr_from_file(argv[1]);
    return 0;
}